//
//  RoomSeclectViewController.m
//  QRMaster
//
//  Created by myApple on 15/4/14.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "RoomSeclectViewController.h"
#import "RequestNetWork.h"
#import "memberRoomModel.h"
#import "AFNetworking.h"
#import "Reachability.h"
#import "PromptInfoView.h"
#import "AllocateBulidingModel.h"
#import "AllocateFloorModel.h"
#import "AllocateRoomModel.h"
#import "AllocateFloorCell.h"
#import "AllocateBulidingHeaderView.h"
#import "RoomSelectNextViewController.h"
#import "MBProgressHUD.h"
#import "validateInputValue.h"
#import "AllocateRoomProcess.h"
#import "EditStaffTimeView.h"
#import "staffRoomTimeCell.h"
#import "FloorSelectController.h"
#import "BuildSelectController.h"

@interface RoomSeclectViewController ()<UITableViewDataSource,UITableViewDelegate,EditStaffTimeViewDelegate>
{
    NSMutableArray * houseDataArray;
    BOOL selectFlag;
    UIButton * allSeclectBtn;
    NSMutableArray * memberRoomArray;//存modle模型数据的
    
    NSMutableArray * saveRoomArray;
    NSArray * dataArray;//网络请求下来的数据源
   
    NSMutableArray * floorArray;
    NSMutableArray * roomArray;
    
    UIView * buttonDeleteView;
    
    NSMutableArray * paramtArray;//准备传递给后台的楼栋楼层json数组
    
    UIView * promtnNoRoomView;//没有房间的提示
    
    NSMutableArray * bulidingArray;
    NSArray * displayArray;
    UITableView * roomShowTableView;
    
    AllocateRoomProcess * dataProcess;
    UIImageView * editImageView;
    EditStaffTimeView * editBackView;
    
    //多语言
    UILabel * titleNameLabel;
    UILabel * promtLable;
    UIButton * btn;
    UILabel * promtTextLabel;
}

@end

@implementation RoomSeclectViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        memberRoomArray = [[NSMutableArray alloc]init];
        saveRoomArray = [[NSMutableArray alloc]init];
        floorArray = [[NSMutableArray alloc]init];
        roomArray = [[NSMutableArray alloc]init];
        dataArray = [[NSArray alloc]init];
        paramtArray = [[NSMutableArray alloc]init];
        selectFlag = NO;
        houseDataArray = [[NSMutableArray alloc]init];
        
        bulidingArray = [[NSMutableArray alloc]init];
        dataProcess = [[AllocateRoomProcess alloc]init];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = NSLocalizedString(@"roomChoose", nil);
    [self prepareTableView];
    [self prepareViewWithNoRoom];
    [self prepareNavBtn];
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    editImageView.hidden = NO;
    [self LookMemberRoomPower];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    editImageView.hidden = YES;
}

-(void)prepareTableView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeigh = UI_SCREEN_HEIGHT - 64;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = ScreenHeigh - y;
    
    roomShowTableView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height) style:UITableViewStylePlain];
    roomShowTableView.delegate = self;
    roomShowTableView.dataSource = self;
    roomShowTableView.tableFooterView = [[UIView alloc]init];
    roomShowTableView.tableFooterView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:roomShowTableView];
}


#pragma mark --------编辑
-(void)prepareNavBtn
{
    editImageView = [[UIImageView alloc]initWithFrame:CGRectMake(UI_SCREEN_WIDTH - 66, 2, 50, 40)];
    editImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer * editTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(edit)];
    [editImageView addGestureRecognizer:editTap];
    [self.navigationController.navigationBar addSubview:editImageView];
    
    UILabel * editLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, 50, 20)];
    editLabel.text = @"编辑";
    editLabel.textColor = UIColorFromRGBAndA(0x7dc234, 1);
    editLabel.font = [UIFont systemFontOfSize:15.0];
    editLabel.textAlignment = NSTextAlignmentRight;
    [editImageView addSubview:editLabel];
    
    editBackView = [[EditStaffTimeView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT)];
    editBackView.backgroundColor = [UIColor clearColor];
    editBackView.delegate = self;
    editBackView.hidden = YES;
    UITapGestureRecognizer * hiddenEditTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenEditView)];
    [editBackView addGestureRecognizer:hiddenEditTap];
    [self.view addSubview:editBackView];
}

-(void)hiddenEditView
{
    editBackView.hidden = YES;
}

-(void)edit
{
    editBackView.hidden = NO;
}

#pragma mark --------EditStaffTimeViewDelelgate
-(void)EditStaffTimeView:(NSInteger)selectIndex
{
    editBackView.hidden = YES;
    switch (selectIndex) {
        case 0:
        {
            RoomSelectNextViewController * rsnvc = [[RoomSelectNextViewController alloc]init];
            rsnvc.guestOrStaff = _guestOrStaff;
            rsnvc.memeberID = _memberid;
            rsnvc.areaCode = _areaCode;
            rsnvc.roomArray = [dataProcess getRoomDataAllocate];
            rsnvc.groupId = _groupId;
            rsnvc.mobile = _mobile;
            rsnvc.email = _email;
            rsnvc.allocatedRoomArray = [[dataProcess getAllocatedRoom]mutableCopy];
            [self.navigationController pushViewController:rsnvc animated:YES];
        }
            break;
        case 1:
        {
            FloorSelectController * rsnvc = [[FloorSelectController alloc]init];
            rsnvc.guestOrStaff = _guestOrStaff;
            rsnvc.memeberID = _memberid;
            rsnvc.areaCode = _areaCode;
            rsnvc.floorArray = [dataProcess getFloorDataAllocate];
            rsnvc.groupId = _groupId;
            rsnvc.mobile = _mobile;
            rsnvc.email = _email;
            rsnvc.allocateFloorArray = [[dataProcess getFloorAllocated]mutableCopy];
            rsnvc.buildingArray = bulidingArray;
            [self.navigationController pushViewController:rsnvc animated:YES];
        }
            break;
        case 2:
        {
            BuildSelectController * rsnvc = [[BuildSelectController alloc]init];
            rsnvc.guestOrStaff = _guestOrStaff;
            rsnvc.memeberID = _memberid;
            rsnvc.areaCode = _areaCode;
            rsnvc.buildDisplayArray = [dataProcess getBuildDataAllocate];
            rsnvc.groupId = _groupId;
            rsnvc.mobile = _mobile;
            rsnvc.email = _email;
            rsnvc.allocateBuildArray = [[dataProcess getBuildAllocated]mutableCopy];
            rsnvc.buildingArray = bulidingArray;
            [self.navigationController pushViewController:rsnvc animated:YES];
        }
            break;
        default:
            break;
    }
}


-(void)LookMemberRoomPower
{
    if ([self IsHaveNetwork]) {
        return;
    }
    NSString *paramStr=@"";
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:_communityid forKey:@"communityId"];
    __block RoomSeclectViewController * weakSelf =self;
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    if ([_guestOrStaff isEqualToString:@"1"]) {
        [postDict setValue:_memberid forKey:@"userId"];
        paramStr=POST(GETONESELFROOM);
    }
    else if([_guestOrStaff isEqualToString:@"0"])
    {
        [postDict setValue:_memberid forKey:@"userId"];
        paramStr=POST(GETCLENTROOM);
    }
    else
    {
        [postDict setValue:_groupId forKey:@"groupId"];
        [postDict setValue:_email forKey:@"email"];
        [postDict setValue:_mobile forKey:@"mobile"];
        if ([validateInputValue isPureNumandCharacters:_mobile] && _mobile != nil && ![_mobile isEqualToString:@""]) {
            [postDict setValue:_areaCode forKey:@"areaCode"];
        }
        paramStr=POST(GETGROUPCLIENTROOM);
        
    }
    [rnw initWithPath:paramStr params:postDict block:^(id downLoadData, id error)
     {
         id data = [downLoadData objectForKey:@"data"];
         if (data) {
             NSArray * roomData = nil;
             if ([_guestOrStaff isEqualToString:@"2"]) {
                 roomData = [data objectForKey:@"roomStatus"];
             }
             else
                 roomData = data;
             [bulidingArray removeAllObjects];
             bulidingArray = [[dataProcess dataProcess:roomData] mutableCopy];
             displayArray = [bulidingArray copy];
             if (bulidingArray.count == 0) {
                 promtnNoRoomView.hidden = NO;
             }
             [roomShowTableView reloadData];
         }
         else
         {
             if ([[error objectForKey:@"status"]intValue] == 301) {
                 [PromptInfoView showMessage:NSLocalizedString(@"noRoomInfo", nil) superView:weakSelf.view];
             }
             else
             {
                 [PromptInfoView showMessage:[error objectForKey:@"info"]];
             }
         }
         [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
     }
     ];
   
}

#pragma mark --------------请求后没有房间
-(void)prepareViewWithNoRoom
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float width;
    float height;
    
    promtnNoRoomView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64)];
    promtnNoRoomView.backgroundColor = RGBA(237, 238, 241, 1);
    promtnNoRoomView.hidden = YES;
    [self.view addSubview:promtnNoRoomView];
    
    NSString * imgPath = [[NSBundle mainBundle]pathForResource:@"没有设置默认房卡" ofType:@"png"];
    UIImage * promImg = [UIImage imageWithContentsOfFile:imgPath];
    height= promImg.size.height * ScreenWidth / 3.0 /promImg.size.width;
    width = ScreenWidth / 3.0;
    UIImageView * promImgView = [[UIImageView alloc]initWithFrame:CGRectMake((self.view.frame.size.width - width)/ 2.0, (self.view.frame.size.height - height)/ 2.0 - 64, width, height)];
    promImgView.image = promImg;
    [promtnNoRoomView addSubview:promImgView];
    
    
    promtTextLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, promImgView.frame.size.height /2.0+promImgView.frame.origin.y + 74, ScreenWidth - 100, 60)];
    promtTextLabel.text = NSLocalizedString(@"makeSureModifyPower", nil);
    promtTextLabel.textColor = RGBA(211, 211, 211, 1);
    promtTextLabel.textAlignment = NSTextAlignmentCenter;
    promtTextLabel.numberOfLines = 0;
    promtTextLabel.font = [UIFont systemFontOfSize:16.0];
    [promtnNoRoomView addSubview:promtTextLabel];
    
}


#pragma mark ------------TableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return displayArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RoomBaseModel * nextModel  = nil;
    if (displayArray.count - 1 > indexPath.row) {
        nextModel = displayArray[indexPath.row + 1];
    }
    RoomBaseModel * model = [displayArray objectAtIndex:indexPath.row];
    if (model.nodeType == NodeTypeGroup) {
        AllocateFloorCell *cell = [AllocateFloorCell cellWithTableView:tableView];
        [cell setData:(ItemModel *) model];
        return cell;
    }
    else
    {
        staffRoomTimeCell *cell = [staffRoomTimeCell cellWithTableView:tableView];
        [cell setData:(AllocateRoomModel *)model];
        if (indexPath.row == displayArray.count - 1) {
            cell.isLastRow = YES;
        }
        else if(nextModel.nodeLevel == 1 && model.nodeLevel == 3)
        {
            cell.isLastRow = YES;
        }
        else
        {
            cell.isLastRow = NO;
        }
        return cell;
    }}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    RoomBaseModel * model = displayArray[indexPath.row];
    if (model.nodeLevel == 3) {
        return;
    }
    model.isExpanded = !model.isExpanded;
    model.isClick = YES;
    [self reloadDisplayArray];
}

#pragma mark --------点击刷新
-(void)reloadDisplayArray
{
    NSMutableArray * tmpList = [[NSMutableArray alloc]init];
    for (ItemModel * model in bulidingArray) {
        if (model.isExpanded) {
            [self addData:model toArray:tmpList];
        }
        else
        {
            [tmpList addObject:model];
        }
    }
    displayArray = [[NSArray arrayWithArray:tmpList] mutableCopy];
    [roomShowTableView reloadData];
}

-(void)addData:(ItemModel *)model toArray:(NSMutableArray *)tmpList
{
    [tmpList addObject:model];
    for (ItemModel * floorModel in model.itemChildrenArray) {
        [tmpList addObject:floorModel];
        if (floorModel.isExpanded) {
            for (AllocateRoomModel * roomModel in floorModel.itemChildrenArray) {
                [tmpList addObject:roomModel];
            }
        }
    }
}


//-(void)makeSureDelete
//{
//    if ([self IsHaveNetwork]) {
//        return;
//    }
//    NSString *paramStr=@"";
//    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
//    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
//    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
//    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
//    [postDict setValue:_communityid forKey:@"communityId"];
//    RequestNetWork * rnw = [[RequestNetWork alloc]init];
//    if ([_guestOrStaff isEqualToString:@"1"]) {
//        [postDict setValue:_memberid forKey:@"userId"];
//        [postDict setValue:[self prepareJson] forKey:@"roomStr"];
//        paramStr = POST(ADDSTAFFFLOOR);
//    }
//    else if([_guestOrStaff isEqualToString:@"0"])
//    {
//        [postDict setValue:_memberid forKey:@"userId"];
//        [postDict setValue:[self prepareJson] forKey:@"roomStr"];
//        
//        paramStr = POST(ADDCLIENTFLOORPOWER);
//    }
//    else
//    {
//        [postDict setValue:_groupId forKey:@"groupId"];
//        [postDict setValue:_email forKey:@"email"];
//        if ([validateInputValue isPureNumandCharacters:_mobile] && _mobile != nil && ![_mobile isEqualToString:@""]) {
//            [postDict setValue:_areaCode forKey:@"areaCode"];
//        }
//        [postDict setValue:_mobile forKey:@"mobile"];
//        [postDict setValue:[self prepareJson] forKey:@"groupRoom"];
//        paramStr = POST(EDITGROUPCLIENTROOM);
//    }
//    [self startWaiting:nil color:nil addToView:self.view];
//    [rnw initWithPath:paramStr  params:postDict block:^(id downLoadData, id error)
//    {
//        [self stopWaiting];
//        if (downLoadData) {
//            [PromptInfoView showMessage:NSLocalizedString(@"modifySuccess", nil) superView:self.view];
//        }
//        else
//        {
//            [PromptInfoView showMessage:[error objectForKey:@"info"] superView:self.view];
//        }
//    
//    }];
//
//    [self clearDelete];
//}
//
//#pragma mark -- 准备json
//-(NSString *)prepareJson
//{
//    [paramtArray removeAllObjects];
//     NSMutableString * RoomStr = [[NSMutableString alloc]init];
//    for (AllocateBulidingModel * bmodel in bulidingArray) {
//        if (bmodel.floorSelect > 0) {
//            for (AllocateFloorModel * fmodel in bmodel.floorArray) {
//                if (fmodel.RoomSelect > 0) {
//                    for (AllocateRoomModel * rmodel in fmodel.RoomArray) {
//                        if (rmodel.isSelect > 0) {
//                            [RoomStr appendString:rmodel.roomid];
//                            [RoomStr appendString:@","];
//                        }
//                    }
//                    
//                }
//            }
//        }
//    }
//    if (RoomStr.length > 1) {
//        NSRange range;
//        range.location = RoomStr.length - 1;
//        range.length = 1;
//        [RoomStr deleteCharactersInRange:range];
//    }
//    return RoomStr;
//}


-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
